package com.huitao.jpegdemo


import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import java.io.ByteArrayOutputStream
import java.io.File
import java.util.logging.Logger

/**
 * author:huitao
 */

private val JPEG_START = byteArrayOf(0xFF.toByte(), 0xD8.toByte())
private val JPEG_END = byteArrayOf(0xFF.toByte(), 0xD9.toByte())

// 定义分隔符（需根据实际 MJPEG 流调整）
private val boundary = "0xFF".toByteArray(Charsets.US_ASCII)

private val buffer = ByteArray(4096) // 缓冲区大小可调整

private const val TAG = "JpegUtil"

suspend fun readJpeg(file: File, block: (ByteArray) -> Unit) = withContext(Dispatchers.IO) {
    val inputStream = file.inputStream().buffered()
    val buffer = ByteArray(8192)
    var bytesInBuffer = 0
    var isFrameStarted = false
    val frameData = ByteArrayOutputStream()

    while (true) {
        // 1. 填充缓冲区
        val readBytes = inputStream.read(buffer, bytesInBuffer, buffer.size - bytesInBuffer)
        Log.d(TAG, "readJpeg: 读取8192字节")
        if (readBytes == -1) break
        bytesInBuffer += readBytes

        // 2. 遍历缓冲区，查找帧头和帧尾
        var i = 0
        while (i < bytesInBuffer - 1) {
            // 检测帧头 0xFFD8
            if (!isFrameStarted && buffer[i] == JPEG_START[0] && buffer[i + 1] == JPEG_START[1]) {
                isFrameStarted = true
                frameData.reset()
                frameData.write(JPEG_START)
                i += 2
            }

            // 检测帧尾 0xFFD9
            if (isFrameStarted && i < bytesInBuffer - 1 &&
                buffer[i] == JPEG_END[0] && buffer[i + 1] == JPEG_END[1]
            ) {
                frameData.write(JPEG_END)
                block(frameData.toByteArray())
                isFrameStarted = false
                i += 2
                //delay(3)
            } else if (isFrameStarted) {
                // 累积帧数据
                frameData.write(byteArrayOf(buffer[i]))
                i++
            } else {
                i++
            }
        }

        // 3. 处理剩余数据（可能跨缓冲区）
        if (isFrameStarted) {
            System.arraycopy(buffer, i, buffer, 0, bytesInBuffer - i)
            bytesInBuffer -= i
        } else {
            bytesInBuffer = 0
        }
    }
}

// 查找分隔符位置
private fun indexOfBoundary(buffer: ByteArray, start: Int, end: Int): Int {
    for (i in start until end - boundary.size + 1) {
        var match = true
        for (j in boundary.indices) {
            if (buffer[i + j] != boundary[j]) {
                match = false
                break
            }
        }
        if (match) return i
    }
    return -1
}

// 跳过分隔符和头部信息
private fun skipBoundaryAndHeaders(boundaryStart: Int): Int {
    var pos = boundaryStart + boundary.size
    // 跳过头部（直到连续两个换行符 "\r\n\r\n"）
    while (pos + 3 < buffer.size) {
        if (buffer[pos] == '\r'.code.toByte() &&
            buffer[pos + 1] == '\n'.code.toByte() &&
            buffer[pos + 2] == '\r'.code.toByte() &&
            buffer[pos + 3] == '\n'.code.toByte()
        ) {
            return pos + 4
        }
        pos++
    }
    return pos
}

// 提取帧数据
private fun extractFrameData(buffer: ByteArray, start: Int, end: Int): ByteArray {
    return buffer.copyOfRange(start, end)
}

